from django.shortcuts import render, redirect, reverse
from django.http import HttpResponse
from django.views.decorators.http import require_POST
from django.views.generic.base import View, TemplateView
from .forms import LoginForm, RegisterForm, EditSchoolForm, EditUserForm, SelectListForm
from .models import User
from schools.models import School
from courses.models import Course
from django.utils.decorators import method_decorator
from .decorators import login_required
from datetime import datetime
from django.db.models import Q


def index(request):
    return render(request, 'index.html')


def sign(request):
    return render(request, 'signup.html')


# 登录视图
class LoginView(View):
    @staticmethod
    def get(request, *args, **kwargs):
        form = LoginForm()
        user = request.front_user
        if user:
            return redirect(reverse('courses:course_list'))
        else:
            return render(request, 'users/login.html', context={'form': form})

    def post(self, request, *args, **kwargs):
        form = LoginForm(request.POST)
        if form.is_valid():
            phone = form.cleaned_data.get('phone')
            password = form.cleaned_data.get('password')
            remember = form.cleaned_data.get('remember')
            # 在用户表和学校表中获取联系电话和密码相同的数据
            user = User.objects.filter(css_phone=phone, css_password=password).first()
            school = School.objects.filter(css_phone=phone, css_password=password).first()
            # 获取成功则保存联系电话到session中，并根据不同角色跳转到相对应的页面，失败则重新登录
            if user or school:
                request.session['user_phone'] = phone
                if remember:
                    # 设置为None，则表示使用全局的过期时间
                    request.session.set_expiry(None)
                else:
                    request.session.set_expiry(0)
                return redirect(reverse("courses:course_list"))
            else:
                return redirect(reverse('users:login'))
        else:
            print(form.errors.get_json_data())
            return HttpResponse('error')


# 注册视图
class RegisterView(View):
    @staticmethod
    def get(request, *args, **kwargs):
        form = RegisterForm()
        user = request.front_user
        schools = School.objects.all()
        if user:
            return redirect(reverse('index'))
        else:
            return render(request, 'users/register.html', context={'form': form, 'schools': schools})

    def post(self, request, *args, **kwargs):
        form = RegisterForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            return redirect(reverse('users:login'))
        else:
            print(form.errors.get_json_data())
            return redirect(reverse('users:register'))


# 用户注销
def logout(request):
    request.session.flush()
    return redirect(reverse('users:login'))


# 信息修改视图
@method_decorator(login_required, name='dispatch')
class EditView(View):
    @staticmethod
    def get(request, *args, **kwargs):
        user = request.front_user
        # 判断角色类型，返回不同的form验证表单和对应的context内容
        if user.css_role == 'school':
            form = EditSchoolForm()
            return render(request, 'schools/edit.html', context={'form': form, 'school': user})
        else:
            schools = School.objects.all()
            form = EditUserForm()
            return render(request, 'users/edit.html', context={'form': form, 'user': user, 'schools': schools})

    def post(self, request, *args, **kwargs):
        # 获取存储在上下文中的用户信息
        user = request.front_user
        # 判断角色类型，对提交的数据进行对应的form表单验证，通过后对提交的数据在不同条件下进行判断选择更新到数据库中
        if user.css_role == 'school':
            # 表单需要上传文件
            form = EditSchoolForm(request.POST, request.FILES)
            if form.is_valid():
                css_image = 'school/' + str(form.cleaned_data.get('css_image'))
                css_name = form.cleaned_data.get('css_name')
                css_phone = form.cleaned_data.get('css_phone')
                css_password = form.cleaned_data.get('css_password')
                css_address = form.cleaned_data.get('css_address')
                css_desc = form.cleaned_data.get('css_desc')
                css_detail = form.cleaned_data.get('css_detail')
                password_new = form.cleaned_data.get('password_new')
                # 原有联系电话和旧密码相同情况下更新数据并注销重新登录
                if css_phone == user.css_phone and css_password == user.css_password:
                    School.objects.filter(pk=user.pk).update(css_image=css_image, css_name=css_name, css_desc=css_desc,
                                                             css_password=password_new, css_address=css_address,
                                                             css_detail=css_detail)
                    request.session.flush()
                    return redirect(reverse('users:login'))
                # 新联系电话和旧密码相同情况下进行处理
                elif css_phone != user.css_phone and css_password == user.css_password:
                    exists_user = User.objects.filter(css_phone=css_phone).exists()
                    exists_school = School.objects.filter(css_phone=css_phone).exists()
                    # 新联系电话是否已经注册，是则返回修改页面重新修改，否则更新数据并注销重新登录
                    if exists_user or exists_school:
                        print('School Edit Error!')
                        return render(request, 'schools/edit.html', context={'form': form, 'front_user': user})
                    else:
                        School.objects.filter(pk=user.pk).update(css_image=css_image, css_name=css_name,
                                                                 css_phone=css_phone, css_password=password_new,
                                                                 css_address=css_address, css_desc=css_desc,
                                                                 css_detail=css_detail)
                        request.session.flush()
                        return redirect(reverse('users:login'))
                # 其他条件下都是修改失败，返回修改页面重新修改
                else:
                    print('School Edit Error!')
                    return render(request, 'schools/edit.html', context={'form': form, 'front_user': user})
            else:
                print('School Edit Error!')
                return render(request, 'schools/edit.html', context={'form': form, 'front_user': user})
        else:
            # 表单需要上传文件
            form = EditUserForm(request.POST, request.FILES)
            if form.is_valid():
                css_id = form.cleaned_data.get('css_id')
                css_image = 'user/' + str(form.cleaned_data.get('css_image'))
                css_name = form.cleaned_data.get('css_name')
                css_password = form.cleaned_data.get('css_password')
                css_gender = form.cleaned_data.get('css_gender')
                css_role = form.cleaned_data.get('css_role')
                css_phone = form.cleaned_data.get('css_phone')
                css_school = form.cleaned_data.get('css_school')
                password_new = form.cleaned_data.get('password_new')
                # 原有联系电话和旧密码相同情况下更新数据并注销重新登录
                if css_phone == user.css_phone and css_password == user.css_password:
                    User.objects.filter(pk=user.pk).update(css_id=css_id, css_image=css_image, css_name=css_name,
                                                           css_password=password_new, css_gender=css_gender,
                                                           css_role=css_role, css_school=css_school)
                    request.session.flush()
                    return redirect(reverse('users:login'))
                # 新联系电话和旧密码相同情况下进行处理
                elif css_phone != user.css_phone and css_password == user.css_password:
                    exists_user = User.objects.filter(css_phone=css_phone).exists()
                    exists_school = School.objects.filter(css_phone=css_phone).exists()
                    if exists_user or exists_school:
                        print(form.errors.get_json_data())
                        print('User Edit Error!')
                        return render(request, 'users/edit.html', context={'form': form, 'front_user': user})
                    else:
                        User.objects.filter(pk=user.pk).update(css_id=css_id, css_image=css_image, css_name=css_name,
                                                               css_password=password_new, css_gender=css_gender,
                                                               css_role=css_role, css_phone=css_phone,
                                                               css_school=css_school)
                        request.session.flush()
                        return redirect(reverse('users:login'))
                # 其他条件下都是修改失败，返回修改页面重新修改
                else:
                    print(form.errors.get_json_data())
                    print('User Edit Error!')
                    return render(request, 'users/edit.html', context={'form': form, 'front_user': user})
            else:
                print(form.errors.get_json_data())
                print('User Edit Error!')
                return render(request, 'users/edit.html', context={'form': form, 'front_user': user})


# 学校开设所有课程视图
@method_decorator(login_required, name='dispatch')
class TeacherListView(View):
    @staticmethod
    def get(request, *args, **kwargs):
        school = request.front_user
        if school.css_role == "school":
            teachers = User.objects.filter(css_school=school.id, css_role="teacher")
            return render(request, "users/teacher_list.html", context={'teachers': teachers})
        else:
            print("您没有此权限查看")
            return redirect(reverse("courses:course_list"))


# 学校所有学生列表视图
@method_decorator(login_required, name='dispatch')
class SchoolStudentListView(View):
    @staticmethod
    def get(request, *args, **kwargs):
        school = request.front_user
        if school.css_role == "school":
            students = User.objects.filter(css_school=school.id, css_role="student")
            return render(request, "users/student_list.html", context={'students': students})
        else:
            print("您没有此权限查看")
            return redirect(reverse("courses:course_list"))


# 学校删除本校学生和教师用户
@method_decorator(login_required, name='dispatch')
class UserDeleteView(View):
    @staticmethod
    def get(request, user_id, *args, **kwargs):
        school = request.front_user
        if school.css_role == "school":
            user = User.objects.get(pk=user_id)
            user.delete()
            return redirect(reverse("users:teacher_list"))
        else:
            print("您没有此权限")
            return redirect(reverse("courses:course_list"))
